// pages/invite/invite.js
import { getUserPermissions, shareOptions } from "../../utils/access";
import api from "../../config/api";
import request from "../../utils/request";
import { jump, getStorage, goBack } from "../../utils/utils";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 二维码图片
    qrcodeSrc:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getQrcode();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.shareSheet = this.selectComponent('#shareSheet')
    this.modal = this.selectComponent("#modal")
    // this.modal.show()
  },
  confirm(){
    this.modal.hide()
    goBack()
  },
  // 显示分享弹窗
  showShareSheet() {
    this.shareSheet.show()
  },
  // 隐藏分享弹窗
  hideShareSheet() {
    this.shareSheet.hide()
  },
  // 获取而我妈
  async getQrcode(){
    const userId = getStorage('userId')
    console.log(userId)
    const fileData = await request.get(api.qrcodeImage, {
      page: 'pages/index/index',
      scene: 'invite_user_id=' + userId
    }, { responseType: 'arraybuffer' })
    console.log(fileData);

    const fileManager = wx.getFileSystemManager()
    const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.jpg`
    console.log(filePath)
    
    fileManager.writeFileSync(filePath, fileData, 'binary')
    this.setData({
      qrcodeSrc: filePath
    })
  },
  // 保存图片到相册
  savePic:function(){
    // 调用系统方法，下载图片并保存
    getUserPermissions('writePhotosAlbum', (res) => {
      if (res) {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })
      } else {
        wx.showToast({
          title: '保存失败',
          icon: 'error'
        })
      }
    }, { filePath: this.data.qrcodeSrc })
  },
  // 跳转邀请列表
  jumpRecords() {
    jump('inviteRecords')
  },
  // 跳转赚钱攻略
  jumpRaiders() {
    jump('inviteRaiders')
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(e) {
    return shareOptions('default', e)
  }
})